# write by hashaki
# first edit on 2018/11/15
# last change on 2018/11/22
# 抽象gateio交易所接口

from hashakisea.constant.chinese import EXCHANGE_GATEIO
from hashakisea.constant.objectClass import tickClass,tradeClass
from hashakisea.api.digital.gateio import GateIO
from hashakisea.api.hagateway import HaGateway
from datetime import datetime,timedelta
from time import sleep

class GateGatewaySimulate:
    def __init__(self,HaEngine):
        self.hagateway=HaGateway(HaEngine)
        self.gateAPI=GateIO()
        self.default_name='default'
        self.forever_run=False
        self.simulateEngine=None

    def connect(self):
        try:
            self.hagateway.onTick(self.gateAPI.marketinfo())
            print("把市场信息注册到事件引擎")
        except Exception as error:
            print("连接交易所出了点问题，问题：",error)
        
    def getTick(self,symbol):
        '''把获取某币种的请求放进函数队列'''
        self.hagateway.onTick(self.gateAPI.ticker(symbol))
        
    def getDepth(self,symbol):
        '''请求市场深度'''
        self.hagateway.onTick(self.gateAPI.orderBook(symbol))
    
    def foreverQry(self,target_symbol_list):
        '''开启无限查询'''
        if not target_symbol_list:
            print("订阅列表为空")
            return 0

        self.forever_run=True
        while self.forever_run:
            for i in target_symbol_list:
                print(self.getTick(i))

            sleep(1)

    def stopQry(self):
        '''停止查询'''
        self.forever_run=False
        self.hagateway.close()
        # TODO:停止查询后，进行持久化操作
    
    def connetSimulateEngine(self,simulateEngine):
        self.simulateEngine=simulateEngine
    # TRADE功能
    def getBalance(self):
        '''获取余额'''
        return self.simulateEngine.broker.cash
    
    def buy(self,target_symbol,volume,price):
        '''买进'''
        self.simulateEngine.broker.buy(target_symbol,volume,price)
    
    def sell(self,target_symbol,volume,price):
        '''卖出'''
        self.simulateEngine.broker.sell(target_symbol,volume,price)

    def cancelOrder(self,orderID):
        '''取消单个订单'''
        self.simulateEngine.broker.cancelOrder(orderID)
    
    def cancelOrders(self):
        '''取消所有订单'''
        self.simulateEngine.broker.cancelOrders()
    
    def orderStatus(self,orderID,symbol):
        '''获取订单状态'''
        pass
    
    def getHistoryTrade(self,orderID,symbol):
        '''获取历史交易'''
        pass